//
//  WNReadManager.swift
//  WalkNovel
//
//  Created by Kevin on 2023/10/23.
//

import UIKit
import AVFoundation

class WNReadManager: NSObject {
    
    static let shared = WNReadManager()
    
    var laungeVoices = [AVSpeechSynthesisVoice.init(language: "en-US"), AVSpeechSynthesisVoice.init(language: "en-GB")]
    
    var synthesizer: AVSpeechSynthesizer?
    
    var readStr = ""
        
    var readClosure: BoolClosure?
    
    func beginReading(_ str: String, _ voice: Int = 0) {
        guard str.count > 0 else {
            return
        }
        readStr = str
        if synthesizer == nil {
            synthesizer = AVSpeechSynthesizer()
            synthesizer?.delegate = self
        }
        let utterance = AVSpeechUtterance.init(string: readStr)
        utterance.voice = laungeVoices[voice]
        utterance.rate = 0.5
        utterance.pitchMultiplier = 0.8 // 声调
        utterance.volume = 1
        utterance.preUtteranceDelay = 0.1 // 阅读下一句的延迟
        utterance.postUtteranceDelay = 0.5 // 开始阅读的延迟
        synthesizer?.speak(utterance)
    }
    
    // 暂停阅读
    func pauseReading() {
        if synthesizer != nil {
            if !synthesizer!.isPaused {
                synthesizer?.pauseSpeaking(at: .word)
                readClosure?(false)
            }
        }
    }
    
    // 继续阅读
    func resumeReading() {
        if synthesizer != nil {
            if synthesizer!.isPaused {
                synthesizer?.continueSpeaking()
            }
        }
    }
    
    // 停止阅读
    func stopReading() {
        if synthesizer != nil {
            if synthesizer!.isSpeaking {
                synthesizer?.stopSpeaking(at: .word)
            }
        }
        readClosure?(false)
    }
}

extension WNReadManager: AVSpeechSynthesizerDelegate {
    
    func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) {
        readClosure?(true)
    }
    
    func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, willSpeakRangeOfSpeechString characterRange: NSRange, utterance: AVSpeechUtterance) {
        let str = utterance.speechString.wn_subString(characterRange)
        WNLog("即将播放的语音文字:\(str)")
    }
}
